<?php
  include_once('colMapping.php');

  $isRegistered = $_REQUEST['isRegistered'] == 'true';

  $bbox = '+'.$_REQUEST['swLat']
    .',+'.$_REQUEST['swLon']
    .',+'.$_REQUEST['neLat']
    .',+'.$_REQUEST['neLon'];

  $sort_by = $isRegistered ? 'parcelnum' : 'phys_city';
  foreach ($cols as $key => $value) {
    if ($_REQUEST['sort'] == $value) {
      $sort_by = $key;
    }
  }
  if ($isRegistered) {
    $sort_by .= ',phys_city';
  }

  $sort_dir = 'A';
  if ($_REQUEST['dir'] == 'DESC') {
    $sort_dir = 'D';
  }

  $regulated_only = '';
  if ($_REQUEST['regulatedOnly'] == 'true') {
    $regulated_only = "+and+regulated='True'";
  }

  $xml = '';
  if ($isRegistered) {
    $owner_name = '%25';
    if (isset($_REQUEST['query']) and $_REQUEST['query'] != '') {
      $owner_name = '%25'.str_replace(' ','%20',$_REQUEST['query']).'%25';
    }
    $xml = simplexml_load_string(file_get_contents("http://geo.bluecityexchange.org/geoserver/crwa/ows?service=WFS&version=1.1.0&request=GetFeature&typeName=crwa:parcels&cql_filter=(phys_city='Milford'+or+phys_city='Bellingham'+or+phys_city='Franklin')+and+BBOX(geom,$bbox)$regulated_only+and+(ownername+like+'$owner_name'+or+parcelnum+like+'$owner_name')&sortBy=$sort_by+$sort_dir&propertyName=phys_addr1,phys_city,parcelnum,ownername,regulated,actrem_lby&maxFeatures=500"));
  }
  else {
    $phys_addr1 = '%25';
    if (isset($_REQUEST['query']) and $_REQUEST['query'] != '') {
      $phys_addr1 = '%25'.str_replace(' ','%20',$_REQUEST['query']).'%25';
    }
    $xml = simplexml_load_string(file_get_contents("http://geo.bluecityexchange.org/geoserver/crwa/ows?service=WFS&version=1.1.0&request=GetFeature&typeName=crwa:parcels&cql_filter=(phys_city='Milford'+or+phys_city='Bellingham'+or+phys_city='Franklin')+and+BBOX(geom,$bbox)$regulated_only+and+(phys_addr1+like+'$phys_addr1')&sortBy=$sort_by+$sort_dir&propertyName=phys_addr1,phys_city,parcelnum,ownername,regulated,actrem_lby&maxFeatures=500"));
  }
  $data = array();
  foreach ($xml->xpath("gml:featureMembers/crwa:parcels") as $node) {
    $parcelnum = $node->xpath('crwa:parcelnum');
    $ownername = $node->xpath('crwa:ownername');
    $regulated = $node->xpath('crwa:regulated');
    $actrem_lby = $node->xpath('crwa:actrem_lby'); 
    $phys_addr1 = $node->xpath('crwa:phys_addr1');
    $phys_city = $node->xpath('crwa:phys_city');
    if ($actrem_lby[0] == '0E-11') {
      $actrem_lby[0] = 0;
    }

    $data[] = array(
       $cols['parcelnum']  => (string)$parcelnum[0]
      ,$cols['ownername']  => (string)$ownername[0]
      ,$cols['regulated']  => (string)$regulated[0]
      ,$cols['actrem_lby'] => (string)$actrem_lby[0]
      ,$cols['phys_addr1'] => (string)$phys_addr1[0]
      ,$cols['phys_city']  => (string)$phys_city[0]
    );
  }

  echo json_encode(array('data' => $data,'count' => count($data)));
?>
